package br.com.gkarian.mydesk.path;

import br.com.caelum.vraptor.http.FormatResolver;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.view.DefaultPathResolver;

@Component
public class CustomPathResolver extends DefaultPathResolver {

	private static final String CONTROLLER = "controller";

	private FormatResolver resolver;

	public CustomPathResolver(FormatResolver resolver) {
		super(resolver);
		this.resolver = resolver;
	}

	@Override
	public String pathFor(ResourceMethod method) {

		String format = resolver.getAcceptFormat();

		String suffix = "";
		if (format != null && !format.equals("html")) {
			suffix = "." + format;
		}

		String name = method.getResource().getType().getSimpleName();
		String folderName = extractControllerFromName(name);
		String pkg = method.getResource().getType().getPackage().getName();

		int indexBegin = pkg.indexOf(CONTROLLER) + CONTROLLER.length();
		if (indexBegin != pkg.length()) {
			indexBegin++;
		}
		
		String subFoldersJsp = pkg.substring(indexBegin, pkg.length());

		String path = getPrefix() + subFoldersJsp + "/" + folderName + "/"
				+ method.getMethod().getName() + suffix + "." + getExtension();

		return path;
	}

	public static void main(String[] args) {
		String pk = "br.com.gkarian.mydesk.controller";

		int indexBegin = pk.indexOf(CONTROLLER) + CONTROLLER.length();

		System.out.println("length = " + pk.length());
		System.out.println("indexBegin = " + indexBegin);

		pk = pk.substring(indexBegin + 1, pk.length());

		System.out.println(pk);
	}
}
